package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mybeans.factory.RollbackException;

import cloudContact.Emailer;
import cloudContact.MyDAOException;
import cloudContact.DAO.UnactivatedUser;
import cloudContact.DAO.UnactivatedUserDAO;
import cloudContact.DAO.UserDAO;

/**
 * Servlet implementation class ValidateRegister
 */
@WebServlet("/ValidateRegister")
public class ValidateRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ValidateRegister() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		try {

			if ((request.getParameter("userName") == null)
					|| request.getParameter("userName").toString().isEmpty()) {
				out.print("Error: Invalid user information");
				return;
			}

			String userName = request.getParameter("userName").toString();

			// Check that user does not exist both in unactivate and user table.
			UnactivatedUserDAO unActDAO = UnactivatedUserDAO.getInstance();
			UserDAO userDAO = UserDAO.getInstance();

			if ((unActDAO.lookup(userName) != null)
					|| (userDAO.lookup(userName) != null)) {
				out.print("Error: The user name already registered.");
				return;
			}

		} catch (RollbackException e) {
			out.print("Error: " + e.toString());
		} catch (MyDAOException e) {
			out.print("Error: " + e.toString());
		} finally {
			out.flush();
			out.close();
		}
	}

}
